#@revision $Revision$ 
#@author Jorge Niedbalski R. <jnr@niedbalski.org>

from Exception   import ListenerException,TaskManagerException
from TaskManager import Task, TaskManager
from Config         import Config

import simplejson as json
import tornado.httpserver
import tornado.ioloop
import tornado.web
import threading
import sys

class    SCQueueListenerHandler(tornado.web.RequestHandler):
    
    _task_id = None

    def   get(self, action):
        pass
        
    def   post(self, action):    
        try:
            if action == 'add':
                argument = self.get_argument('task')
                if argument:
                    task_id = TaskManager.addTaskToQueueFromListener(argument)    
            self.sendWorking(task_id)
                                    
        except TaskManagerException as e:
            self.sendError(e, self._task_id)

    def   sendWorking(self, task_id):
        print json.JSONEncoder().encode({ 'status' : TaskManager.TASK_WORKING, 'task_id' : task_id})
        return

    def   sendError(self, message, task_id):
        print json.JSONEncoder().encode({ 'status' : TaskManager.TASK_ERROR, 'task_id' : task_id, 'data' : message._str_() })
        return

    def   admin(self):
        pass

    def   listCurrentTasks(self):
        pass

    def   job(self, args):
        pass

class    Listener(threading.Thread):

        _loop  = None
        
        def   _init_(self, exceptionQueue):
            self._exceptionQueue = exceptionQueue
            self._port           = int(Config.getServerListener()['port'])
            threading.Thread._init_(self)

        def   run(self):
            try:
                application = tornado.web.Application([
                                                       (r"/squeue/(.*)", SCQueueListenerHandler),
                                                      ])

                self._http_server = tornado.httpserver.HTTPServer(application)
                self._http_server.listen(self._port)
            
                self._loop = tornado.ioloop.IOLoop.instance()
                self.startLoop()
                
            except Exception as e:
                self._exceptionQueue.put(e)

        def   startLoop(self):
            if Config.DEBUG:
                print "Starting HTTP listener on port %s" % ( self._port
            self._loop.start()

        def   stop(self):
            if Config.DEBUG:
                print "Stopping HTTP listener on port %s" % ( self._port
            self._loop.stop()
            sys.exit(0)
